/*
 * Copyright 2006 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.user.client.ui;

import com.google.gwt.user.client.DOM;

/**
 * A panel that displays all of its child widgets in a 'deck', where only one
 * can be visible at a time. It is used by
 * {@link com.google.gwt.user.client.ui.TabPanel}.
 */
public class DeckPanel extends ComplexPanel {

  private int visibleWidget = -1;

  /**
   * Creates an empty deck panel.
   */
  public DeckPanel() {
    setElement(DOM.createDiv());
  }

  public boolean add(Widget w) {
    return insert(w, getWidgetCount());
  }

  /**
   * Gets the index of the currently-visible widget.
   * 
   * @return the visible widget's index
   */
  public int getVisibleWidget() {
    return visibleWidget;
  }

  public boolean insert(Widget w, int beforeIndex) {
    super.add(w);
    DOM.appendChild(getElement(), w.getElement());

    DOM.setStyleAttribute(w.getElement(), "width", "100%");
    DOM.setStyleAttribute(w.getElement(), "height", "100%");
    UIObject.setVisible(w.getElement(), false);
    return true;
  }

  public boolean remove(Widget w) {
    if (!super.remove(w))
      return false;
    DOM.removeChild(getElement(), w.getElement());
    return true;
  }

  /**
   * Shows the widget at the specified index. This causes the currently- visible
   * widget to be hidden.
   * 
   * @param index the index of the widget to be shown
   */
  public void showWidget(int index) {
    if (visibleWidget != -1) {
      Widget oldWidget = getWidget(visibleWidget);
      UIObject.setVisible(oldWidget.getElement(), false);
    }

    visibleWidget = index;

    Widget newWidget = getWidget(visibleWidget);
    UIObject.setVisible(newWidget.getElement(), true);
  }
}
